package eiisan.async;

import eiisan.config.aop.log.annotation.DurationLog;
import eiisan.config.aop.log.annotation.MethodLog;
import eiisan.config.aop.log.annotation.ResultLog;
import eiisan.config.aop.request.annotation.TimeoutLock;
import eiisan.config.aop.validation.annotation.Check;
import eiisan.dao.domain.user.Permission;
import eiisan.dao.repository.user.PermissionRepository;
import eiisan.util.model.param.QueryPage;
import eiisan.util.model.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFuture;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

@Component
@Transactional
public class AsyncService {

    @Autowired
    private PermissionRepository permissionRepository;

    @Check
    @MethodLog
    @ResultLog
    @DurationLog(threshold = 10)
    @TimeoutLock(10)
    public ListenableFuture<Result> async(@Valid @NotNull QueryPage param) {
        System.out.println("1111111111" + param.getPageSize());
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Result.errorServe().async();
        }
        Integer pageNum = param.getPageNum();
        Integer pageSize = param.getPageSize();
        PageRequest pageRequest =  PageRequest.of(pageNum, pageSize);
//        Page<Permission> pages = permissionRepository.findAll(pageRequest);
        long end = System.currentTimeMillis();
        System.out.println("异步任务耗时: " + param.getPageSize() + (end - start) + "毫秒");
        return Result.success("异步任务耗时" + param.getPageSize()).async();
    }

    @Check
    @MethodLog
    @ResultLog
    @DurationLog(threshold = 10)
    @TimeoutLock(10)
    public Result result(@Valid @NotNull QueryPage param) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Result.errorServe();
        }
        Integer pageNum = param.getPageNum();
        Integer pageSize = param.getPageSize();
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
        Page<Permission> pages = permissionRepository.findAll(pageRequest);
        return Result.page(pages);
    }

}
